//subPackages2/pages/wallet/tradeDetail/tradeDetail// pages/biz/wallet/tradeDetail/tradeDetail.js
import Serv from '../walletServ'

var regeneratorRuntime = require('../../../../lib/js/runtime-module.js')
const util = require('../../../../utils/util2.js')
import config from '../../../../utils/config2'

const date = new Date()
const years = []
const months = []

for (let i = 1990; i <= date.getFullYear(); i++) {
  years.push(i)
}

for (let i = 1; i <= (date.getMonth() + 1); i++) {
  if (i < 10) {
    i = '0' + i
  }
  months.push(i)
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageNo: 1,
    commissionPageNo: 1,
    total: 1,
    user_id: '',
    // 时间选择
    years: years,
    months: months,
    dateValue: date.format('yyyy-MM-dd').split('-'),
    selectValue: date.format('yyyy-MM-dd').split('-'),
    value: [years.length + 1, 0],
    // 显示弹窗
    isShowModal: false,
    redPacketList: [],
    commissionList: [],
    tabActive: 'commission'
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.changeTab(this.data.tabActive);
  },
  //切换tab
  changeTab(e) {
    let { selectValue } = this.data;
    let tabActive = e.currentTarget ? e.currentTarget.dataset.name : e
    if (tabActive == 'commission') {
      this.data.query_time = selectValue[0] + '-' + selectValue[1]
      this.data.commissionPageNo = 1;
      this.data.commissionList = [];
      this.queryAccountDetail()
    } else {
      this.data.pageNo = 1;
      this.data.redPacketList = [];
      this.getTradeDetail()
    }
    this.setData({
      tabActive
    });
  },
  //跳转到详情页
  router: function (e) {
    let index = e.currentTarget.dataset.index
    let currentItem = this.data.commissionList[index] || {}
    let id = currentItem['txn_seqno']//交易流水号
    if (currentItem.txn_type !== 'ACCT_CASH_OUT') {
      return false
    }
    wx.redirectTo({
      url: `../cashOutResult/cashOutResult?id=${id}`,
    })
  },

  // 日期选择器
  bindChange: function (e) {
    const val = e.detail.value
    let arr = [this.data.years[val[0]], this.data.months[val[1]],]
    let nowYear = date.getFullYear(), months = [],
      nowMoths = this.data.years[val[0]] == nowYear ? (date.getMonth() + 1) : 12; //过滤时间

    for (let i = 1; i <= nowMoths; i++) {
      if (i < 10) {
        i = '0' + i
      }
      months.push(i)
    }
    this.setData({
      selectValue: arr, months
    })
  },
  //弹窗显示与关闭
  showModal: function (e) {
    let btnType = e.currentTarget.dataset.type
    let { selectValue, dateValue, tabActive } = this.data
    let value = e.currentTarget.dataset.type == 'confirm' ? this.data.selectValue : this.data.dateValue
    if (btnType == 'confirm') {
      value = selectValue
      this.data.query_time = value[0] + '-' + value[1]
      if (tabActive == 'commission') {
        this.data.commissionList = []
        this.queryAccountDetail()
      } else {
        this.data.redPacketList = []
        this.getTradeDetail()
      }

    } else {
      value = dateValue
    }
    this.setData({
      isShowModal: !this.data.isShowModal,
      dateValue: value,
    })
  },


  // 交易明细列表 accountId  query_time pageNo page_size  sort_type
  queryAccountDetail: async function () {
    let { query_time, commissionList = [], user_id, commissionPageNo } = this.data
    //发起请求
    let params = {
      accountId: user_id,
      query_time,
      pageNo: commissionPageNo,
      pageSize: 11,
      sort_type: 'DESC',//排序方式，DESC，时间降序/ASC,时间升序，默认降序
    }
    let { success, msg, data } = await Serv.queryAccountDetail(params)
    if (!success) {
      wx.showToast({
        title: msg || '',
        icon: 'none',
      })
      return false
    }
    commissionList = commissionList.concat(data)
    this.setData({
      commissionList: commissionList || []
    })

  },

  //下拉刷新
  onPullDownRefresh: function () {
    let _this = this
    wx.showNavigationBarLoading() //在标题栏中显示加载
    if (_this.data.tabActive == 'commission') {
      _this.data.commissionPageNo = 1
      _this.queryAccountDetail()
    } else {
      _this.data.pageNo = 1
      _this.getTradeDetail()
    }

    // complete
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  //加载更多
  onReachBottom: function () {
    let { pageNo, total, redPacketList, commissionPageNo, tabActive } = this.data
    let _this = this
    wx.showNavigationBarLoading() //在标题栏中显示加载
    if (tabActive == 'commission') {
      _this.data.commissionPageNo = commissionPageNo + 1
      _this.queryAccountDetail()
      
    } else {
      if (redPacketList.length < total) {
        _this.data.pageNo = pageNo + 1
        _this.getTradeDetail()
      }
    }
    // complete
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user_id = wx.getStorageSync(config.userIdKey)
    this.setData({ user_id })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 跳转账单详情
   */
  goDetailAccount(e) {
    let { index } = e.currentTarget.dataset;
    let detailAccount = this.data.redPacketList[index];
    wx.navigateTo({
      url: `/subPackages/pages/redPacket/detailAccount/detailAccount?redPacketId=${detailAccount.redPacketId}`
    });
  },
  /**
   * 查询用户红包明细
   */
  async getTradeDetail() {
    let myAccountId = wx.getStorageSync('userId');
    let param = {
      pageNo: this.data.pageNo,
      pageSize: 11,
      senderAccountId: myAccountId,
      recipientAccountId: myAccountId,
      year: this.data.selectValue[0],
      month: this.data.selectValue[1]
    }
    let { redPacketList } = this.data;
    let { success, rows, total } = await Serv.redPacketRecord(param)
    if (!success) {
      wx.showToast({
        title: msg || '',
        icon: 'none',
      })
      return false
    }
    redPacketList = redPacketList.concat(rows)
    this.setData({ redPacketList, total })
  }
})
